package com.fengpb.friday.conductor.service;

import com.fengpb.friday.conductor.cache.CacheKeyEnum;
import com.fengpb.friday.conductor.cache.LocalWorkflowDefCache;
import io.lettuce.core.pubsub.RedisPubSubListener;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.api.listener.MessageListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
public class CacheRefreshService {

    private static final Logger log = LoggerFactory.getLogger(CacheRefreshService.class);

    private final LocalWorkflowDefCache workflowDefCache;

    private final RedissonClient redissonClient;

    public CacheRefreshService(LocalWorkflowDefCache workflowDefCache, RedissonClient redissonClient) {
        this.workflowDefCache = workflowDefCache;
        this.redissonClient = redissonClient;
    }

    /**
     * 发布缓存刷新
     * @param cacheType
     * @param key
     */
    public void pushCacheRefreshSignal(String cacheType, String key) {
        redissonClient.getTopic(CacheKeyEnum.refresh_local_workflow_def_topic.key())
                .publish(cacheType + "|" + key);
    }

    /**
     * 发布缓存删除
     * @param cacheType
     * @param key
     */
    public void pushCacheDeleteSignal(String cacheType, String key) {
        redissonClient.getTopic(CacheKeyEnum.delete_local_workflow_def_topic.key()).publish(cacheType + "|" + key);
    }

    @PostConstruct
    void subscribeRefreshSignal() {
        log.info("订阅缓存刷新信号-开始");
        redissonClient.getTopic(CacheKeyEnum.refresh_local_workflow_def_topic.key())
                .addListener(String.class, (channel, msg) -> doCacheRefresh(msg));
        log.info("订阅缓存刷新信号-结束");
        log.info("订阅缓存删除信号-开始");
        redissonClient.getTopic(CacheKeyEnum.delete_local_workflow_def_topic.key())
                .addListener(String.class, ((channel, msg) -> doCacheDelete(msg)));
        log.info("订阅缓存删除信号-结束");
    }

    /**
     * 按缓存类型刷新缓存
     * @param msg 消息
     */
    private void doCacheRefresh(String msg) {
        String[] arr = msg.split("\\|");
        String cacheType = arr[0];
        String key = arr[1];
        if (CacheKeyEnum.local_workflow_def_cache.name().equals(cacheType)) {
            workflowDefCache.refresh(key);
        }
        log.info("写操作触发本地缓存主动刷新-完成，key：{}，刷新缓存类型：{}", key, cacheType);
    }

    /**
     * 按缓存类型删除
     * @param msg 消息 TODO
     */
    private void doCacheDelete(String msg) {
        String[] arr = msg.split("\\|");
        String cacheType = arr[0];
        String key = arr[1];
        log.info("写操作触发本地缓存主动删除-完成，key{}，删除缓存类型：{}", key, cacheType);
    }
}
